package com.easylinkin.linkappapi.roster.controller;

import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.common.utils.async.AsyncUtil;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.config.dao.SysDictItemMapper;
import com.easylinkin.linkappapi.config.dao.SysDictMapper;
import com.easylinkin.linkappapi.config.entity.SysDict;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.lobar.dto.UserProjectDTO;
import com.easylinkin.linkappapi.lobar.dto.excel.ExcelResultDTO;
import com.easylinkin.linkappapi.lobar.dto.excel.ExcelResultDetailDTO;
import com.easylinkin.linkappapi.operatelog.LogHelper;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant;
import com.easylinkin.linkappapi.roster.dto.LaborTeamDTO;
import com.easylinkin.linkappapi.roster.dto.LinkappRosterPersonnelDTO;
import com.easylinkin.linkappapi.roster.dto.RosterTypeEnum;
import com.easylinkin.linkappapi.roster.entity.LaborTeam;
import com.easylinkin.linkappapi.roster.entity.RailLinkappRosterPersonnel;
import com.easylinkin.linkappapi.roster.mapper.LaborTeamMapper;
import com.easylinkin.linkappapi.roster.service.ILinkappRosterPersonnelService;
import com.easylinkin.linkappapi.roster.vo.LinkappRosterPersonnelVO;
import com.easylinkin.linkappapi.roster.vo.RosterExportVO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 人员花名册服务接口
 * @author lyk
 * @date 2025/6/10 下午 4:59
 */
@RestController
@RequestMapping("/rosterPersonnel")
public class RosterPersonnelController {

    @Resource
    private ILinkappRosterPersonnelService linkappRosterPersonnelService;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;
    @Autowired
    private SysDictItemMapper sysDictItemMapper;
    @Autowired
    private SysDictMapper sysDictMapper;
    @Autowired
    private LaborTeamMapper laborTeamMapper;
    /**
     * 分页列表查询
     */
    @PostMapping("/getPage")
    public RestMessage selectPage(@RequestBody RequestModel<LinkappRosterPersonnelDTO> requestModel) {
     //   Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        IPage<LinkappRosterPersonnelVO> record = linkappRosterPersonnelService.selectPage(requestModel.getPage(), requestModel.getCustomQueryParams());
        /**
         * 处理证书
         */
        if (RosterTypeEnum.SPECIAL_OPERATION.getValue().equals(requestModel.getCustomQueryParams().getRosterType())){
            linkappRosterPersonnelService.specialAuthBookFz(record);
        }
        return RestBuilders.successBuilder(record).build();
    }

    /**
     * 分页列表查询
     */
    @PostMapping("/getList")
    public RestMessage getList(@RequestBody LinkappRosterPersonnelDTO requestModel) {

        List<LinkappRosterPersonnelVO> record = linkappRosterPersonnelService.selecList(requestModel);

        return RestBuilders.successBuilder(record).build();
    }

    /**
     * 管理人员和劳务人员的新增接口
     * @param requestModel
     * @return
     */
    @PostMapping(value = "/managAndStaff.save")
    public RestMessage managAndStaffSave(@RequestBody LinkappRosterPersonnelDTO requestModel){
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        requestModel.setTenantId(tenantId);
        String  rosterType = requestModel.getRosterType();
        if (RosterTypeEnum.CONTRACT_WORKERS.getValue().equals(rosterType)||RosterTypeEnum.MANAGER.getValue().equals(rosterType)){
            return RestBuilders.successBuilder().success((linkappRosterPersonnelService.managAndStaffSave(requestModel))).message("操作成功").build();
        }else {
            return RestBuilders.failureMessage().setMessage("当前接口只能新增管理人员和劳务人员");
        }
    }

    /**
     * 防护员和特种作业人员新增接口
     */
    @PostMapping(value = "/protectAndSpecial.save")
    public RestMessage  protectAndSpecialSave(@RequestBody Map<String,Object> parameters){
        String id = Objects.toString(parameters.get("id"), "");
        if (StringUtils.isEmpty(id)){
            return RestBuilders.failureMessage().setMessage("人员记录id不能为空");
        }
        return RestBuilders.successBuilder().success((linkappRosterPersonnelService.protectAndSpecialSave(parameters))).message("操作成功").build();
    }

    /**
     * 通用修改接口
     * @return
     */
    @PostMapping(value = "/roster.edit")
    public RestMessage rosterEdit(@RequestBody LinkappRosterPersonnelDTO LinkappRosterPersonnelDTO){
        if (Objects.isNull(LinkappRosterPersonnelDTO.getId())){
            return RestBuilders.failureBuilder().message("记录id不能为空").build();
        }
        LinkappRosterPersonnelDTO.setRosterType(null);
        return RestBuilders.successBuilder().success(linkappRosterPersonnelService.rosterEdit(LinkappRosterPersonnelDTO)).message("操作成功").build();
    }
    /**
     * 通用删除接口（可批量）
     */
    @GetMapping(value = "/roster.del")
    public RestMessage rosterDel(String ids){
        if (StringUtils.isEmpty(ids)){
            return RestBuilders.failureBuilder().message("记录id不能为空").build();
        }
        return RestBuilders.successBuilder().success(linkappRosterPersonnelService.rosterDel(ids)).message("操作成功").build();
    }
    /**
     * 防护员和特种作业人员删除接口
     */
    @GetMapping(value = "/rosterByUpdateType")
    public RestMessage rosterByUpdateType(String ids,String rosterType){
        if (StringUtils.isEmpty(ids)){
            return RestBuilders.failureBuilder().message("记录id不能为空").build();
        }
        if (StringUtils.isEmpty(rosterType)){
            return RestBuilders.failureBuilder().message("删除类型不能为空").build();
        }
        if (rosterType.equals(RosterTypeEnum.PROTECTIVE_OFFICER.getValue()) || rosterType.equals(RosterTypeEnum.SPECIAL_OPERATION.getValue())){
            return RestBuilders.successBuilder().success(linkappRosterPersonnelService.rosterByUpdateType(ids,rosterType)).message("操作成功").build();
        }else{
            return RestBuilders.failureBuilder().message("rosterType非法输入").build();
        }
    }
    /**
     * 人员退场接口（可批量）
     * @param ids
     * @return
     */
    @GetMapping(value = "/roster.backAndExec")
    public RestMessage rosterBack(String ids,String time,String flag){
        if (StringUtils.isEmpty(ids)){
            return RestBuilders.failureBuilder().message("记录id不能为空").build();
        }
        if (StringUtils.isEmpty(flag)){
            return RestBuilders.failureBuilder().message("操作指令不能为空").build();
        }
        if (StringUtils.isEmpty(time)){
            return RestBuilders.failureBuilder().message("操作指令不能为空").build();
        }
        RestMessage res = null;
        try {
             res = RestBuilders.successBuilder().success(linkappRosterPersonnelService.rosterBack(ids, time, flag)).message("操作成功").build();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 人员入场接口（可批量）
     * @param ids
     * @param startTime
     * @return
     */
 /*   @GetMapping(value = "/roster.exec")
    public RestMessage rosterExec(String ids,String startTime){
        if (StringUtils.isEmpty(ids)){
            return RestBuilders.failureBuilder().message("记录id不能为空").build();
        }
        return RestBuilders.successBuilder().success(linkappRosterPersonnelService.rosterExec(ids,startTime)).message("操作成功").build();

    }*/

    /**
     *
     * @param ids 人员记录id,多条记录逗号拼接
     * @param gatePermis  闸机记录id,多条记录逗号拼接
     * @return
     */
    @GetMapping(value = "/roster.auths")
    public RestMessage rosterAuths(String ids,String gatePermis){
        if (StringUtils.isEmpty(ids)){
            return RestBuilders.failureBuilder().message("记录id不能为空").build();
        }
        if (StringUtils.isEmpty(gatePermis)){
            return RestBuilders.failureBuilder().message("闸机记录id不能为空").build();
        }
        return RestBuilders.successBuilder().success(linkappRosterPersonnelService.rosterAuths(ids,gatePermis)).message("操作成功").build();
    }

    /**
     * 劳务人员导入模板下载接口
     * @param request
     * @param response
     */
    @GetMapping(value = "/rosterTemplate.down")
    public void rosterTemplateDown(HttpServletRequest request, HttpServletResponse response){
        String title_f = "劳务人员信息";
        String title = "rosterTemplate";
        String fileName = title + ".xlsx";
        try {
            OutputStream outputStream = OutputStreamUtil.getOutputStream(request, response, fileName);
            String keyValue = "姓名(必填*):realName,性别(必填*):sex,工种(必填*):workType,"
                    + "身份证号码(必填*):idsNo,联系电话(必填*):linkPhone,劳务队伍(必填*):laborTeam";
            //创建验证信息
            // 3. 设置下拉列表的作用范围 (示例：A2-A100单元格)
            //性别
            CellRangeAddressList cellRange1 = new CellRangeAddressList(
                    2,   // 起始行 (0-based)
                    999,  // 结束行
                    1,   // 起始列 (0-based=A列)
                    1    // 结束列
            );
            //工种
            CellRangeAddressList cellRange2 = new CellRangeAddressList(
                    2,   // 起始行 (0-based)
                    999,  // 结束行
                    2,   // 起始列 (0-based=A列)
                    2    // 结束列
            );
            //劳务队伍
            CellRangeAddressList cellRange3 = new CellRangeAddressList(
                    2,   // 起始行 (0-based)
                    999,  // 结束行
                    5,   // 起始列 (0-based=A列)
                    5    // 结束列
            );
            List<CellRangeAddressList> CellRangeAddressLists = new ArrayList<>();
            CellRangeAddressLists.add(cellRange1);
            CellRangeAddressLists.add(cellRange2);
            CellRangeAddressLists.add(cellRange3);
            //性别
            List<String> sex = new ArrayList();
            sex.add("男");
            sex.add("女");
            //工种
            // 如果缓存中没有，则从数据库查询
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("dict_code_", "work_type");
            SysDict sysDict = sysDictMapper.selectOne(queryWrapper);
            if (Objects.isNull(sysDict)){
                   return;
            }
            QueryWrapper<SysDictItem> itemQueryWrapper = new QueryWrapper();
            itemQueryWrapper.eq("dict_id_", sysDict.getId());
            List<SysDictItem> list = sysDictItemMapper.selectList(itemQueryWrapper);
            List<String> gz = new ArrayList();
            for (SysDictItem lis:list){
                gz.add(lis.getItemText());
            }
            //劳务队伍
            List<String> lw = new ArrayList();
            LaborTeamDTO  lwdwDTO = new LaborTeamDTO();
            lwdwDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
            List<LaborTeam> laborTeams = laborTeamMapper.listPage(lwdwDTO);
            for (LaborTeam lt:laborTeams){
                if (StringUtils.isNotEmpty(lt.getLaborTeamName())){
                    lw.add(lt.getLaborTeamName());
                }
            }
            ExcelTools.exportExcel(outputStream, keyValue, LinkappRosterPersonnelDTO.creatExcel(), ExcelConstant.XLSX,title_f,CellRangeAddressLists,sex,gz,lw);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException("excel导出失败！IOException异常");
        } catch (Exception e) {
            throw new RuntimeException("excel导出失败！");
        }
    }

    /**
     * 人员信息劳务人员信息导入接口
     * @param file 劳务人员名单excel表格
     * @return
     */
    @PostMapping(value = "/rosterTemplate.import")
    public RestMessage rosterTemplateImport(@NotNull @RequestPart("file") MultipartFile file){
        //记录日志
        if(file != null){
            String fileName = file.getOriginalFilename();
            LogHelper.setContent(LogConstant.LogOperateType.LABOL_USER_BATCH_IMPORT, fileName);
        }
        //获取当前时间的时间
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "rosterProject:"+formatter.format(calendar.getTime());
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        ExcelResultDTO excelResultDTO = null;
        try {
            excelResultDTO = linkappRosterPersonnelService.importRosterExcelCheck(file, tenantId);
            if (excelResultDTO.getFail()>0){
                int size = excelResultDTO.getExcelResultDetailDTOS().size();
                if (size>0){
                    return RestBuilders.failureMessage("第"+excelResultDTO.getExcelResultDetailDTOS().get(0).getNo()+"行:"+excelResultDTO.getExcelResultDetailDTOS().get(0).getDetail());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        AsyncUtil.submitTask(key,() ->{
            ExcelResultDTO resultDTO;
            try {
                resultDTO = linkappRosterPersonnelService.importRosterExcel(file,tenantId);
            } catch (Exception e) {
                throw new BusinessException(e.getMessage());
            }
            return resultDTO;
        });
        return RestBuilders.successBuilder().data(key).build();
    }

    /**
     *  劳务人员导出
     * @param request
     * @param response
     * @param requestModel 分页查询条件
     */
    @PostMapping(value = "/rosterLabor.export")
    public void rosterLaborExport(HttpServletRequest request, HttpServletResponse response,@RequestBody RequestModel<LinkappRosterPersonnelDTO> requestModel){
        requestModel.getPage().setSize(-1);
        if (!RosterTypeEnum.CONTRACT_WORKERS.getValue().equals(requestModel.getCustomQueryParams().getRosterType())){
            Assert.isTrue(false, "此接口只能导出劳务人员记录");
        }
        IPage<LinkappRosterPersonnelVO> record = linkappRosterPersonnelService.selectPage(requestModel.getPage(), requestModel.getCustomQueryParams());
        List<LinkappRosterPersonnelVO> records = record.getRecords();
        //内容转义
        List<RosterExportVO> rosterExportVO = new ArrayList<>();
        for(LinkappRosterPersonnelVO  rosterpPersonnel:records){
            RosterExportVO vo = new RosterExportVO();
            vo.setRealName(rosterpPersonnel.getRealName());
            vo.setIdsNo(StringUtils.isEmpty(rosterpPersonnel.getIdsNo())?"":rosterpPersonnel.getIdsNo());
            vo.setLinkPhone(rosterpPersonnel.getLinkPhone());
            //劳务队伍
            vo.setLaborTeamName(rosterpPersonnel.getLaborTeamName());
            vo.setWorkStatusName(Integer.valueOf(0).equals(rosterpPersonnel.getWorkStatus())?"退场":Integer.valueOf(1).equals(rosterpPersonnel.getWorkStatus())?"在岗":"");
            //年龄
            if (StringUtils.isEmpty(vo.getIdsNo())){
                vo.setAge("");
            }else{
                if (vo.getIdsNo().length()==18 || vo.getIdsNo().length()==15){
                    int ageByIdCard = IdcardUtil.getAgeByIdCard(vo.getIdsNo());
                    vo.setAge(ageByIdCard+"岁");
                }
            }
            vo.setWorkTypeName("");
            //工种查询
            if (!StringUtils.isEmpty(rosterpPersonnel.getWorkType())){
                SysDictItem work_type = linkappRosterPersonnelService.getDict("work_type", rosterpPersonnel.getWorkType());
                if (!Objects.isNull(work_type)){
                    vo.setWorkTypeName(work_type.getItemText());
                }
            }
            //入场退场时间
            vo.setStartAndEndDate("~");
            if (!Objects.isNull(rosterpPersonnel.getStartTime())){
                vo.setStartAndEndDate(DateUtil.getYYYYMMDDHHMMSSDate(rosterpPersonnel.getStartTime())+"-");
            }
            if (!Objects.isNull(rosterpPersonnel.getEndTime())){
                vo.setStartAndEndDate(vo.getStartAndEndDate()+DateUtil.getYYYYMMDDHHMMSSDate(rosterpPersonnel.getEndTime()));
            }
            rosterExportVO.add(vo);
        }
        String keyValue = "姓名:realName,年龄:age,身份证号码:idsNo,联系电话:linkPhone,劳务队伍:laborTeamName,在岗状态:workStatusName," +
                "工种:workTypeName,入场时间/退场时间:startAndEndDate";
        String title_name = "劳务人员信息";
        String fileName = "rosterTemplate";
        fileName = fileName + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil.getOutputStream(request, response, fileName);
            ExcelTools.exportExcel(outputStream, keyValue, rosterExportVO, ExcelConstant.XLS, title_name);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }





}
